import dayjs from "dayjs";
import CryptoJS from "crypto-js";
export function getRandomInt(max) {
	return Math.floor(Math.random() * max);
}
export function jsonToParse(string:any) {
	if (typeof string == 'string') {
		try {
			return JSON.parse(string);
		}catch(e) {
			return string;
		}
	}
	return string;
}
export function  wholeToParse(string:any){
	const obj:any = jsonToParse(string);
	if (typeof obj == "object" && obj) {
		for(const key in obj){
			obj[key]=wholeToParse(obj[key])
		}
	}
	return obj;
}
export function createElement(text,style?:string){
	const div = document.createElement("div");
    div.innerHTML=text;div.style.cssText=style || "";
	return div;
}
export function timeFormat(date:any,format:any){
   return date? dayjs(date).format(format):"";
}
export function getRandomId(number=32){
	let result = "";
	const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
	for (let i = 0; i < chars.length; i++)  result += chars.charAt(Math.floor(Math.random() * chars.length));
	return  result;
}
export function getRandomTime(){
   return new Date().getTime();
}
export function JsonArryToArray(target:any,key:any){
	const result:any[] = [];
	target.forEach((item:any)=>{
		if(["",null,undefined].indexOf(item[key]) == -1) {
			result.push(item[key]);
		}
	})
	return result;
}
export function debounce(fn, delay, immediate?) {
	let timer;
	return function (this: any, ...args: any[]) {
		if (timer) clearTimeout(timer);
		if (immediate) {
			// 复杂的防抖函数
			// 判断定时器是否为空，如果为空，则会直接执行回调函数
			const firstRun = !timer;
			// 不管定时器是否为空，都会重新开启一个新的定时器,不断输入，不断开启新的定时器，当不在输入的delay后，再次输入就会立即执行回调函数
			timer = setTimeout(() => {
				timer = null;
			}, delay);
			if (firstRun) {
				fn.apply(this, args);
			}
			// 简单的防抖函数
		} else {
			timer = setTimeout(() => {
				fn.apply(this, args);
			}, delay);
		}
	};
}
export function setJsonArrayValue(json,key,value){
   json.forEach(item=>{
	   item[key]=value;
   })
}
//改写数据字段
function charChange(json:any,replace:Function){
	const result:any = Array.isArray(json) ? [] : {};
	if(Array.isArray(json)){
		json.forEach((item:any)=> {
			result.push(charChange(item,replace));
		})
	}else{
		for(const key in json){
			const replaceKey = replace(key);
			result[replaceKey] = json[key];
			if(typeof json[key] == "object") {
				result[replaceKey] = charChange(json[key],replace);
			}
		}
	}
	return result;
}
/*
* 大驼峰改链式命名
* */
function getBTLReplaceName(key:any) {
	return key.replace(/([a-z]+)([A-Z]{1})/g,function(params,first,last) {
		return first+"_"+last.toLowerCase();
	})
}
export function bigToLower(json:any){
	return charChange(json,getBTLReplaceName);
}
/*链式命名改大驼峰*/
function getLTBReplaceName(key:any) {
	return key.replace(/(-)([a-z]{1})/g,function(params,first,last) {
		return last.toUpperCase();
	})
}
export function lowerTobig(json:any){
	return charChange(json,getBTLReplaceName);
}
/*判断是否有值合并json*/
export function assign(target:any,value:any){
	for(const key in value){
        if([null,undefined,""].indexOf(value[key]) == -1){
			target[key] = value[key];
		}
		continue;
	}
}
/*
* 获取地址栏参数
* */
export function getUrlSearch(name:string) {
	// 未传参，返回空
	if (!name) return null;
	// 查询参数：先通过search取值，如果取不到就通过hash来取
	let after = window.location.search;
	after = after.substr(1) || window.location.hash.split("?")[1];
	// 地址栏URL没有查询参数，返回空
	if (!after) return null;
	// 如果查询参数中没有"name"，返回空
	if (after.indexOf(name) === -1) return null;

	const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
	// 当地址栏参数存在中文时，需要解码，不然会乱码
	const r = decodeURI(after).match(reg);
	// 如果url中"name"没有值，返回空
	if (!r) return null;

	return r[2];
}
export function urlAddQuery(url,query){
	if(query.value && url.indexOf(query.key)==-1){
		return (url.indexOf("?")!=-1? "&":"?")+query.key+"="+query.value;
	}
	return "";
}
/*
*CryptoJS 加密解密
* */
export const crypto={
	SECRET_KEY : CryptoJS.enc.Utf8.parse("1234123412341234"),
	SECRET_IV : CryptoJS.enc.Utf8.parse("1234123412341234"),
	//加密
	encode:function(data) {
		if (typeof data === "object") {
			try {
				// eslint-disable-next-line no-param-reassign
				data = JSON.stringify(data);
			} catch (error) {
				console.log("encrypt error:", error);
			}
		}
		const dataHex = CryptoJS.enc.Utf8.parse(data);
		const encrypted = CryptoJS.AES.encrypt(dataHex, this.SECRET_KEY, {
			iv: this.SECRET_IV,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return encrypted.ciphertext.toString();
	},
	//解密
	decode(data) {
		const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
		const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
		const decrypt = CryptoJS.AES.decrypt(str, this.SECRET_KEY, {
			iv: this.SECRET_IV,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
		return decryptedStr.toString();
	},
}
